import re
import socket


class Method:
    """通用方法类"""
    @staticmethod
    def __reg_placeholder(text: str, res: list) -> str:
        """根据re.findall结果进行%s占位符处理"""
        if len(res) == 1:
            result = res[0]
            # 单次与多次匹配处理
            if type(result) == str:
                text = text.replace("%s", result)
            elif type(result) == tuple:
                # 倒序替换以兼容10以上%s
                index_list = list(range(len(result)))
                index_list.reverse()
                for i in index_list:
                    text = text.replace(f"%s{i + 1}", result[i])
                text = text.replace("%s", result[0])
        return text

    @classmethod
    def deal_placeholder(cls, text: str, res: list, plain="") -> str:
        """根据re.findall结果进行%p, %s占位符处理"""
        text = cls.__reg_placeholder(text, res)
        if plain:
            text = text.replace("%p", plain)
        return text

    @staticmethod
    def del_info_header(pattern: str, pla: str) -> str:
        """去除输出头部信息"""
        re_pla = re.search(pattern, pla)
        if re_pla:
            return re_pla.group().strip()
        return pla

    @staticmethod
    def deal_cq_tags(text: str) -> str:
        """处理@消息、简化CQ码显示与特殊字符替换"""
        # @消息转化为qq号
        res = re.findall("(?<=\\[CQ:at,qq=).+?(?=[,\\]])", text)
        for uid in res:
            text = re.sub(f"\\[CQ:at,qq={uid}.*?]", uid, text)
        # 简化CQ码, 去重之后再检索替换
        cq_tags: set = set(re.findall("(?<=\\[CQ:).+?(?=[,\\]])", text))
        for cq_tag in cq_tags:
            text = re.sub(f"\\[CQ:{cq_tag}.*?]", f"[CQ:{cq_tag}]", text)
        text = (text.replace("&amp;", "&").replace("&#91;", "[")
                .replace("&#93;", "]").replace("&#44;", ","))
        return text

    @staticmethod
    def deal_at_tags(text: str) -> str:
        """将QQ官方接口@消息转换为ID"""
        res = re.findall("(?<=<@!).+?(?=>)", text)
        for uid in res:
            text = re.sub(f"<@!{uid}>", uid, text)
        return text

    @staticmethod
    def get_host_by_name(url: str) -> str:
        """优先使用ipv6"""
        try:
            host = f"[{socket.getaddrinfo(url, None, socket.AF_INET6)[0][4][0]}]"
        except socket.gaierror:
            host = socket.gethostbyname(url)
        return host
